package main

import (
	"flag"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"server/common"
	"server/initialize"
	"server/internal/model"
	"server/internal/router"
	"server/internal/router/manager"
	"server/logger"
	"server/pkg/app"
	"server/pkg/setting"
	"time"
)

var (
	port    string
	runMode string
	config  string
)

func setupLogger() error {
	logger.InitLogger(logger.LogConfig{
		InfoFilePath:  "/var/log/ptool/ptool_info.log",
		ErrorFilePath: "/var/log/ptool/ptool_error.log",
		MaxSizeMB:     500,   // 单文件最大100MB
		MaxBackupDays: 10,    // 保留30天
		EnableConsole: false, // 开发环境启用控制台
	})
	return nil
}

func setupFlag() error {
	flag.StringVar(&port, "port", "", "监听端口")
	flag.StringVar(&runMode, "mode", "", "启动模式")
	flag.StringVar(&config, "config", "configs/", "配置文件路径")
	flag.Parse()
	return nil
}

func setupDBEngine() error {
	var err error
	common.DB, err = model.NewDBEngine(setting.Database)
	if err != nil {
		return err
	}
	manager.InitCasbin(setting.Database)
	initialize.TnitTable()
	initialize.InitCasbin()

	app.InitBigCache()
	initialize.InitMeauList()
	return nil
}

func setupSetting() error {
	sets, err := setting.NewSetting()
	if err != nil {
		return err
	}
	err = sets.ReadSection("Server", &setting.Server)
	if err != nil {
		return err
	}
	err = sets.ReadSection("App", &setting.App)
	if err != nil {
		return err
	}
	err = sets.ReadSection("Database", &setting.Database)
	if err != nil {
		return err
	}
	err = sets.ReadSection("JWT", &setting.JWT)
	if err != nil {
		return err
	}
	setting.App.DefaultContextTimeout *= time.Second
	setting.JWT.Expire *= time.Second
	setting.Server.ReadTimeout *= time.Second
	setting.Server.WriteTimeout *= time.Second
	if port != "" {
		setting.Server.HttpPort = port
	}
	if runMode != "" {
		setting.Server.RunMode = runMode
	}
	return nil
}

func init() {
	err := setupFlag()
	if err != nil {
		log.Fatalf("init.setupFlag err: %v", err)
	}
	err = setupSetting()
	if err != nil {
		log.Fatalf("init.setupSetting err: %v", err)
	}
	//初始化数据库
	err = setupDBEngine()
	if err != nil {
		log.Fatalf("init.setupDBEngine err: %v", err)
	}
	err = setupLogger()
	if err != nil {
		log.Fatalf("init.setupLogger err: %v", err)
	}
}

func main() {
	gin.SetMode(setting.Server.RunMode)
	r := router.NewRouter()
	s := &http.Server{
		Addr:           ":" + setting.Server.HttpPort,
		Handler:        r,
		ReadTimeout:    setting.Server.ReadTimeout,
		WriteTimeout:   setting.Server.WriteTimeout,
		MaxHeaderBytes: 1 << 20,
	}
	_ = s.ListenAndServe()
}
